package jmind.core.manager;

import java.util.concurrent.FutureTask;

import jmind.core.redis.NioRedis;
import jmind.core.redis.Redis;
import jmind.core.redis.RedisCluster;
import jmind.base.util.DataUtil;

/**
 * redis管理类，有nio的类自动加载nio，否则使用jedis
 启动服务
/usr/local/redis/bin/redis-server /usr/local/redis/etc/redis.conf

停止服务
/usr/local/redis/bin/redis-cli shutdown
 * 
 * redis.z-account.host 192.168.0.215:9531,192.168.0.216:9531
 * @author wbxie
 * 2014-1-26
 */
public class RedisManager extends AbstractManager<Redis> {

    private static volatile RedisManager manager;

    public static RedisManager getInstance() {
        if (manager == null) {
            synchronized (RedisManager.class) {
                if (manager == null) {
                    manager = new RedisManager();
                }
            }

        }
        return manager;
    }

    @Override
    public Redis create(String name) {
        final String hosts = getProperties().getProperty("redis." + name + ".host");
        // 超时时间，单位秒，默认30
        int timeout = DataUtil.toInt(getProperties().getProperty("redis." + name + ".timeout", "30"));
        Redis redis;
        try {
            Class.forName("jmind.redis.RedisBootstrap2");
            redis = new NioRedis(hosts, timeout);
            logger.debug("init nio redis {}={}, timeout={}", name, hosts, timeout);
        } catch (ClassNotFoundException e) {
            String mode = getProperties().getProperty("redis." + name + ".mode");

            logger.debug("init  jedis {}={}, timeout={}", name, hosts, timeout);
         //   if ("cluster".equals(mode)) {
                redis = new RedisCluster(name, getProperties());
//            } else {
//                if (hosts.contains(",")) {
//                    redis = new ShardedRedis(name, getProperties());
//                } else {
//                    redis = new SingleJedis(name, getProperties());
//                }
//            }

        }

        return redis;

    }

    @Override
    public void releaseResource() {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                for (FutureTask<Redis> redis : RESOURCES.values()) {
                    try {
                        redis.get().releaseResource();
                    } catch (Exception e) {
                        logger.error("", e);
                    }

                }
                logger.debug("releaseResource {}", getClass().getName());
            }
        });

    }

}
